var Error = require('http-errors');
var express = require('express');

var path  = require('path');

var app = express();

const stringRandom = require('string-random');

var Tdate = require("silly-datetime");
//-----------------------------
//导入数据库
const mysql = require('mysql');
const db = mysql.createConnection({
    host:"127.0.0.1",
    port:3306,
    user:"root",
    password:"maple0513",
    database:"NEU"
});
//连接数据库
db.connect(err=>{
    //如果发生错误，抛异常
    if(err) throw  err;
    console.log('数据库连接成功');
});


app.listen(4000, ()=>{
    console.log('服务器开启成功')
});

app.all('*',function (req,res,next) {
        res.header("Access-Control-Allow-Origin","*");
        res.header("Access-Control-Allow-Headers","X-Requested-With,Content-Type");
        res.header("Access-Control-Allow-Methods","POST,GET,OPTION,DELETE");
        next();
    }
);

app.get('/Login',function(req,res,next){
    var params = req.query || req.params;
    console.log(params.phoneNum);
    console.log(params.pass);
    db.query("SELECT * FROM user where phoneNum = ? and password= ?",[params.phoneNum,params.pass],function (error, response,result) {
        if(error){
            console.log(error);
        }
        var flag = false;
        if (response.length>0) {
            flag = true;
        }
        
        var result1 = {};
        if (flag) {
            result1 = {
                code: 200,
                msg: "success"
            }
        } else {
            result1 = {
                code: 500,
                msg: 'fail'
            }
        }
        res.jsonp(result1);
    });
})

app.get('/register',function(req,res,next){
    var params = req.query || req.params;

    db.query("INSERT INTO user (phoneNum,password) VALUES (?,?)",[params.phoneNum,params.psw],function (error,response,result) {
        var flag = false;
        if (response) {
            flag = true;
        }

        var data = {};
        data.flag = flag;
        res.jsonp(data);
    });
});

app.get('/getUser',function(req,res,next){
    var params = req.query || req.params;
    db.query("SELECT * FROM user where phoneNum = ?",[params.phoneNum],function (error, response,result) {
        if(error){
            console.log(error);
        }
        var data={};
        var flag=false;
        if(response.length>0){
        	flag=true;
        	data.phoneNum=response[0].phoneNum;
        	data.nickName=response[0].nickName;
        	data.realName=response[0].realName;
        	data.idCard=response[0].idCard;
        	data.gender=response[0].gender;
        	data.totalMoney=response[0].totalMoney;
        }
        var result1={};
        if(flag){
        	result1.Code=0;
        	result1.Data=data;
        }else{
        	result1.Code=1;
        	result1.Msg="用户信息获取失败，请重新登录";
        }
        res.jsonp(result1);
    });
})

app.get('/getUserFund',function(req,res,next){
    var params = req.query || req.params;
    db.query("SELECT * FROM user_fund join funds where user_fund.phoneNum = ? and user_fund.fundID=funds.FCODE",[params.phoneNum],function (error, response,result) {
        if(error){
            console.log(error);
        }
        var datas=[];
        var flag=false;
        if(response.length>0){
        	flag=true;
        }
        for(var i=0;i<response.length;i++){
        	var data={};
        	data.fundID=response[i].fundID;
        	data.phoneNum=response[i].phoneNum;
        	data.hold=response[i].hold;
        	data.hands=response[i].hands;
            data.fundName=response[i].SHORTNAME;
            data.price=response[i].DWJZ;
            data.holding_income=data.hands*data.price-data.hold;
            if(data.holding_income<0){
                data.color='green';
            }else{
                data.color='red';
            }
        	datas.push(data);
        }
        var result1={};
        if(flag){
        	result1.Code=0;
        	result1.Data=datas;
        }else{
        	result1.Code=1;
            var data={};
            data.fundID='000000';
            data.phoneNum='';
            data.hold=0;
            data.hands=0;
            data.fundName='赶快购入第一笔基金吧';
            data.price=0;
            data.holding_income=data.hands*data.price-data.hold;
            datas.push(data);
        	result1.Data=datas;
        }
        console.log(result1);
        res.jsonp(result1);
    });
})

app.get('/setUserFund',function(req,res,next){
    var params = req.query || req.params;
    db.query("INSERT INTO user_fund VALUES (?,?,?,?,?);",[params.fundID,params.phoneNum,params.hold,params.hands,0],function (error, response,result) {
        var result1={};
        if(error){
            console.log(error);
            result1.Code=1;
            result1.Msg="买入失败";
        }else{
        	result1.Code=0;
        	result1.Data={
        		"id":params.fundID,
        		"phoneNum":params.phoneNum,
        		"Msg":"买入成功"
        	}
        }
        res.jsonp(result1);
    });
})

app.get("/user_circle",function(req,res,next){
	var params = req.query || req.params;
	db.query("SELECT * FROM user_circle where userID = ?",[params.userID],function (error, response,result) {
		if(error){
            console.log(error);
        }
        var datas=[];
        var flag=false;
        if(response.length>0){
        	flag=true;
        }
        for(var i=0;i<response.length;i++){
        	var data={};
        	data.userID=response[i].userID;
        	data.circleID=response[i].circleID;
        	datas.push(data);
        }
        var result1={};
        if(flag){
        	result1.Code=0;
        	result1.Data=datas;
        	result1.msg="查询成功";
        }else{
        	result1.Code=1;
        	result1.Msg="查询失败";
        }
        res.jsonp(result1);
	});
})

app.get('/blogs',function(req,res,next){
    var params = req.query || req.params;
    db.query("SELECT * FROM blogs where phoneNum = ?",[params.phoneNum],function (error, response,result) {
        if(error){
            console.log(error);
        }
        var datas=[];
        var flag=false;
        if(response.length>0){
        	flag=true;
        }
        for(var i=0;i<response.length;i++){
        	var data={};
        	data.blogID=response[i].blogID;
        	data.phoneNum=response[i].phoneNum;
        	data.words=response[i].words;
        	data.imgs=response[i].imgs;
        	data.pubTime=response[i].pubTime;
        	data.likes=response[i].likes;
        	data.type=response[i].type;
        	datas.push(data);
        }
        var result1={};
        if(flag){
        	result1.Code=0;
        	result1.Data=datas;
        	result1.msg="查询成功";
        }else{
        	result1.Code=1;
        	result1.Msg="查询失败";
        }
        res.jsonp(result1);
    });
})

app.get('/getBankCard',function(req,res,next){
    var params = req.query || req.params;
    db.query("SELECT * FROM bankcard where phoneNum = ?",[params.phoneNum],function (error, response,result) {
        if(error){
            console.log(error);
        }
        var datas=[];
        var flag=false;
        if(response.length>0){
        	flag=true;
        }
        for(var i=0;i<response.length;i++){
        	datas.push(response[i].bankCard);
        }
        var result1={};
        if(flag){
        	result1.Code=0;
        	result1.Data=datas;
        }else{
        	result1.Code=1;
        	result1.Msg="用户没有绑定银行卡";
        }
        res.jsonp(result1);
    });
})

app.get('/getBlogComment',function(req,res,next){
    var params = req.query || req.params;
    db.query("SELECT * FROM blogcomment where blogID = ?",[params.blogID],function (error, response,result) {
        if(error){
            console.log(error);
        }
        var datas=[];
        var flag=false;
        if(response.length>0){
        	flag=true;
        }
        for(var i=0;i<response.length;i++){
        	var data={
        		"bolgID":response[i].blogID,
        		"comment":response[i].comment,
        		"com_phone_num":response[i].com_phone_num,
        		"commentID":response[i].commentID
        	};
        	datas.push(data);
        }
        var result1={};
        if(flag){
        	result1.Code=0;
        	result1.Data=datas;
        }else{
        	result1.Code=1;
        	result1.Msg="动态没有评论";
        }
        res.jsonp(result1);
    });
})

app.get('/setBlogs',function(req,res,next){
    var blogID=stringRandom(20, '0123456789');
    var today = Tdate.format(new Date(),'YYYY-MM-DD');
    var params = req.query || req.params;
    db.query("insert into blogs values (?,?,?,?,?,?,?)",[blogID,params.phoneNum,params.words,params.imgs,today,0,params.type],function (error, response,result) {
        var result1={};
        if(error){
            result1.Code=0;
            result1.Msg="插入失败";
        }else{
            result1.Code=1;
            result1.Msg="插入成功";
        }
        res.jsonp(result1);
    });
})


app.get('/getFunds',function(req,res,next){
    var params = req.query || req.params;
    db.query("select * from funds where FCODE=?;",[params.fundID],function (error, response,result) {
        var result1={};
        if(error){
            result1.Code=0;
            result1.Msg="插入失败";
        }else if(response.length<1){
            result1.Code=0;
            result1.Msg="数据库中无该基金数据";
        }else{
            result1.Data=response[0];
            result1.Code=1;
            result1.Msg="插入成功";
        }
        res.jsonp(result1);
    });
})

app.get('/getFundList',function(req,res,next){
    var params = req.query || req.params;
    db.query("select * from funds where FTYPE=? order by ? desc;",[params.FTYPE,params.Col],function (error, response,result) {
        var result1={};
        if(error){
            result1.Code=0;
            result1.Msg="插入失败";
        }else if(response.length<1){
            result1.Code=0;
            result1.Msg="数据库中无该基金数据";
        }else{
            result1.Data=response;
            result1.Code=1;
            result1.Msg="插入成功";
        }
        res.jsonp(result1);
    });
})

app.get('/setArticle',function(req,res,next){
    var articleID=stringRandom(20, '0123456789');
    var params = req.query || req.params;
    db.query("insert into article values (?,?,?,?)",[articleID,params.phoneNum,params.title,params.text],function (error, response,result) {
        var result1={};
        if(error){
            result1.Code=0;
            result1.Msg="插入失败";
        }else{
            result1.Code=1;
            result1.Msg="插入成功";
        }
        res.jsonp(result1);
    });
})

app.get('/checkUser',function(req,res,next){
    var params = req.query || req.params;
    db.query("select * from user where phoneNum=?",[params.phoneNum],function (error, response,result) {
        var result1={};
        if(error||response.length>0){
            result1.Code=0;
            result1.Msg="该号码已注册";
        }else{
            result1.Code=1;
            result1.Msg="该号码可用";
        }
        res.jsonp(result1);
    });
})


//取评论
app.get('/getBlogComment',function(req,res,next){
    var params = req.query || req.params;
    db.query("SELECT * FROM blogcomment where blogID = ?",[params.blogID],function (error, response,result) {
        if(error){
            console.log(error);
        }
        var datas=[];
        var flag=false;
        if(response.length>0){
            flag=true;
        }
        for(var i=0;i<response.length;i++){
            var data={
                "blogID":response[i].blogID,
                "comment":response[i].comment,
                "com_phone_num":response[i].com_phone_num,
                "commentID":response[i].commentID
            };
            datas.push(data);
        }
        var result1={};
        if(flag){
            result1.Code=0;
            result1.Data=datas;
        }else{
            result1.Code=1;
            result1.Msg="动态没有评论";
        }
        res.jsonp(result1);
    });
});

//写评论
app.get('/setBlogComment',function(req,res,next){
    var params = req.query || req.params;

    db.query("INSERT INTO blogcomment VALUES(?,?,?,?);",[params.blogID,params.comment,params.com_phone_num,params.commentID],function (error, response,result) {
        if(error){
            console.log(error);
        }
        var flag=false;
        if(response){
            flag=true;
        }

        var result1={};
        if(flag){
            result1.Code=0;
        }else{
            result1.Code=1;
            result1.Msg="失败";
        }
        res.jsonp(result1);
    });
});

//获取昵称
app.get("/getNickName",function (req,res,next) {
    var params = req.query || req.params;
    db.query("SELECT nickName FROM user WHERE phoneNum=?",[params.phoneNum],function (err,resp,result) {
        if(err){
            console.log(err);
        }
        var flag = false;
        if(resp.length>0){
            flag = true;
        }
        var result1={};
        if(flag){
            result1.Code=0;
            result1.Data=resp[0].nickName;
        }else{
            result1.Code=1;
            result1.Msg="动态没有评论";
        }
        res.jsonp(result1);
    })
});

//点赞
app.get("/addLikes",function (req,res,next) {
    let params = req.query || req.params;

    var sql = "update blogs set likes=? where blogID=?;";
    db.query(sql,[params.likes,params.blogID],function (err,resp,result) {
        var flag = false;
        if(resp){
            flag = true;
        }
        var data = {}
        if(flag){
            data.code = 0;
            data.msg = "success";
        }else{
            data.code = 1;
            data.msg = "fail"
        }
    })
});



//获取动态数据
app.get("/hot_blog",function (req,res,next) {
    //查询一定热度的blogs
    let params = req.query || req.params;
    //可以设计赞数前百分之20作为热门，暂时设置1000
    var sql = "SELECT * FROM blogs WHERE likes>1000;";
    db.query(sql,"",function (err,resp,result) {

        var flag = false;
        if(resp){
            flag = true;
        }
        for(var i = 0;i<resp.length;i++){
            resp[i].imgs = resp[i].imgs.split(';');
        }
        var data = {};
        if(flag){
            data.code = 0;
            data.msg = "success";
            data.res = resp;
        }else{
            data.code = 1;
            data.msg = "fail"
        }

        res.jsonp(data);

    })
});


app.get('/getBlog',function(req,res,next){
    var params = req.query || req.params;
    db.query("SELECT * FROM blogs where blogID = ?",[params.blogID],function (error, response,result) {
        if(error){
            console.log(error);
        }
        var datas=[];
        var flag=false;
        if(response.length>0){
            flag=true;
        }
        for(var i=0;i<response.length;i++){
            var data={};
            data.blogID=response[i].blogID;
            data.phoneNum=response[i].phoneNum;
            data.words=response[i].words;
            data.imgs=response[i].imgs.split(';');
            data.pubTime=response[i].pubTime;
            data.likes=response[i].likes;
            data.type=response[i].type;
            datas.push(data);
        }
        var result1={};
        if(flag){
            result1.Code=0;
            result1.Data=datas;
            result1.msg="查询成功";
        }else{
            result1.Code=1;
            result1.Msg="查询失败";
        }
        res.jsonp(result1);
    });
});